package org.oos.auth;

import java.io.IOException;
import java.util.List;

import org.oos.atom.AtomService.HttpStatusException;
import org.oos.dao.options.OptionsMap;

import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpMethod;
import com.google.api.client.http.HttpParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;

public class OAuthAuthentication extends AbstractAuthentication {

	private static final long serialVersionUID = -3658120908358951004L;

	private String consumerKey;

	private String consumerSecret;

	private String accessToken;

	private String tokenSecret;

	private transient OAuthParameters authorizer;

	public String getConsumerKey() {
		return consumerKey;
	}

	public String getAccessToken() {
		return accessToken;
	}

	public OAuthAuthentication(String consumerKey, String consumerSecret,
			String accessToken, String tokenSecret) {
		this.consumerKey = consumerKey;
		this.accessToken = accessToken;
		this.consumerSecret = consumerSecret;
		this.tokenSecret = tokenSecret;
	}

	private OAuthParameters getAuthorizer() {
		if (authorizer == null) {
			// Signer
			OAuthHmacSigner signer = new OAuthHmacSigner();
			signer.clientSharedSecret = consumerSecret;
			signer.tokenSharedSecret = tokenSecret;

			// Authorizer
			this.authorizer = new OAuthParameters();
			authorizer.consumerKey = consumerKey;
			authorizer.token = accessToken;
			authorizer.signer = signer;
		}
		return authorizer;
	}

	@Override
	public HttpResponse getResponse(HttpTransport transport, GenericUrl url,
			HttpMethod method, HttpContent content, List<OptionsMap> parameters, HttpParser parser)
			throws IOException, HttpStatusException {
		try {
			HttpRequestFactory factory = transport.createRequestFactory(getAuthorizer());
			url = pack(url, parameters);
			HttpRequest request = factory.buildRequest(method, url, content);
			request.addParser(parser);
			HttpResponse response = request.execute();
			return response;
		} catch (HttpResponseException e) {
			HttpStatusException exception = new HttpStatusException(e
					.getResponse().getStatusCode(), "URL: " + url + " - "
					+ e.getMessage());
			exception.setResponse(e.getResponse());
			throw exception;
		}
	}

	@Override
	public boolean isAnonymous() {
		return false;
	}

}
